/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月14日 下午2:09:13 
 * 
 */
package phoenics.upservice.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import phoenics.upservice.service.JwtService;

/**
 *
 */
@Component
public class JwtTokenFilter implements Filter {  
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(JwtTokenFilter.class);
	private JwtService jwtService;  
	  
    public JwtTokenFilter(@Autowired JwtService jwtService){  
        this.jwtService = jwtService;  
    }  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest servletRequest = (HttpServletRequest) request;  
        String authorization = servletRequest.getHeader("Authorization");  
        if (authorization != null && authorization.startsWith("Bearer ")) {  
            jwtService  
              .parse(authorization.replaceAll("Bearer ", ""))  
             .ifPresent(jwtAuthentication -> SecurityContextHolder  
                .getContext()
                .setAuthentication(jwtAuthentication)); 
        }  
        chain.doFilter(request, response);  
    }  
  
    @Override  
    public void destroy() {  
    }  
}
